package impl

import (
	"github.com/RaymondCode/simple-demo/entity/po"
	"github.com/RaymondCode/simple-demo/repository"
	"gorm.io/gorm"
	"sync"
)

type Favorite struct {

}

func (f Favorite) Insert(favorite *po.Favorite, tx *gorm.DB, isTx bool) error{
	var db1 *gorm.DB
	if isTx {
		db1 = tx
	} else {
		db1 = db
	}
	return db1.Model(po.Favorite{}).Select([]string{"video_id", "user_id"}).Create(favorite).Error
}

func (f Favorite) QueryVideoIdByUserId(userId int) ([]int, error){
	var videoIds = make([]int, 5)
	var favorites = make([]po.Favorite, 5)
	err := db.Model(po.Favorite{}).Select("video_id").Where("user_id = ?", userId).Find(&videoIds).Error
	if err != nil{
		return nil, err
	}
	for _, video := range favorites{
		videoIds = append(videoIds, video.VideoId)
	}
	return videoIds, nil
}

func (f Favorite) DeleteByCondition(favorite *po.Favorite, tx *gorm.DB, isTx bool) error{
	var db1 *gorm.DB
	if isTx {
		db1 = tx
	} else {
		db1 = db
	}
	if favorite.VideoId != 0{
		db1 = db1.Where("video_id = ?", favorite.VideoId)
	}
	if favorite.UserId != 0{
		db1 = db1.Where("user_id = ?", favorite.UserId)
	}
	return db1.Model(po.Favorite{}).Delete(&po.Favorite{}).Error
}

var (
	favorite repository.Favorite
	favoriteOnce sync.Once
)

func NewFavoriteDaoInstance() repository.Favorite{
	favoriteOnce.Do(func() {
		favorite = Favorite{}
	})
	return favorite
}
